﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Runtime.Caching;
using blackhouse.Data;
using blackhouse.WebNemo.Business;
using blackhouse.WebNemo.Data.Cache;

namespace blackhouse.StareKino.Web.Discounts {
    public class FirstMinuteDiscount : Aparts.Web.Discounts.FirstTimeDiscount {

        #region Fields

        private const string Ckey = "firstminutediscount";

        #endregion

        protected override Dictionary<int, List<FirstTimeData>> GetDbData() {
            Dictionary<int, List<FirstTimeData>> data = null;

            if (MemoryCache.Default.Contains(Ckey))
                data = (Dictionary<int, List<FirstTimeData>>)MemoryCache.Default[Ckey];
            if (data == null) {
                data = new Dictionary<int, List<FirstTimeData>>();
                var reader = this.GetDataReader();
                while (reader.Read()) {
                    int apartmentTypeId;
                    var di = this.ReadItem(reader, out apartmentTypeId);
                    if (!data.ContainsKey(apartmentTypeId))
                        data.Add(apartmentTypeId, new List<FirstTimeData>());
                    data[apartmentTypeId].Add(di);
                }
                reader.Close();
                this.SetCache(data);
            }
            return data;
        }

        private void SetCache(object cacheObj) {
            var cip = new CacheItemPolicy();
            cip.SlidingExpiration = TimeSpan.FromMinutes(20);
            cip.ChangeMonitors.Add(new NemoChangeMonitor(new CacheGroupIdsProvider("APARTAMENTY", "Z_CENA__FIRST")));
            var ci = new CacheItem(Ckey, cacheObj);
            MemoryCache.Default.Add(ci, cip);
        }

        private IDataReader GetDataReader() {
            var dataHelper = new MsSqlAdoDataHelper(ConfigurationManager.AppSettings["MSSQLConnectionString"]);
            dataHelper.ProcedureName = "bhp_DiscountsFirstGet";
            return dataHelper.Execute();
        }

        private FirstTimeData ReadItem(IDataReader reader, out int apartmentTypeId) {
            apartmentTypeId = Convert.ToInt32(reader["ApartmentTypeId"]);
            return new FirstTimeData
            {
                Days = Convert.ToInt32(reader["DayCount"]),
                Rabat = Convert.ToSingle(reader["Rabat"])
            };
        }

    }
}